/* Copyright 203-2115 AtomWare Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * The flowing information must be keep 
 * FileUtils.java
 * wholebasic
 * 2014年4月11日上午10:46:25
 * @author 屈甲康
 * QQ285799123
 * mailto:qujiakang@gmail.com
 */

package org.jackysoft.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUtils {

	private static final Log logger = LogFactory.getLog(FileUtils.class);
	public static void reverseFile(int bufsize, String tmpfile,String outfile) {
		InputStream ins = null;
		try {
			

			ins = new BufferedInputStream(new FileInputStream(tmpfile));

			int len = ins.available();
			
			@SuppressWarnings("resource")
			MappedByteBuffer from = new RandomAccessFile(tmpfile, "r")
					.getChannel().map(MapMode.READ_ONLY, 0, len);

			@SuppressWarnings("resource")
			MappedByteBuffer to = new RandomAccessFile(outfile,
					"rw").getChannel().map(MapMode.READ_WRITE, 0, len);
			int last = len % bufsize;
			int b = len / bufsize;

			// b = 3;
			if (b == 0) {
			
				ByteArrayOutputStream outs = new ByteArrayOutputStream();
				
				IOUtils.copyLarge(ins, outs);
				byte[] narray = outs.toByteArray();
				ArrayUtils.reverse(narray);
				to.put(narray);
			} else {
				byte[] buf = new byte[bufsize];
				for (int i = 0; i < b; i++) {
					from.get(buf);
					ArrayUtils.reverse(buf);
					int j = last + (b - i - 1) * bufsize;
					to.position(j);
					to.put(buf, 0, buf.length);

				}
				byte[] lbuf = new byte[last];
				from.get(lbuf);
				ArrayUtils.reverse(lbuf);
				to.position(0);
				to.put(lbuf);
			}
			ins.close();
		} catch (IOException e) {
			logger.error(e);
			try {
				ins.close();
			} catch (IOException e1) {
				logger.error(e1);
				
			}
		}		
	}
	

}
